from .user_input_handler import UserInputHandler
from .data_handler import DataHandler
from .query_executor import QueryExecutor
from .result_presenter import ResultPresenter
from .session_manager import SessionManager
from .memory_handler import MemoryHandler

class QueryProcessor:
    def __init__(self, user_input, file_path, api_endpoint, model_name, explanation_file=None):
        self.data_handler = DataHandler(file_path, explanation_file)
        self.session_manager = SessionManager()
        self.memory_handler = MemoryHandler()
        self.user_input_handler = None
        self.query_executor = None
        self.result_presenter = None
        self.user_input = user_input
        self.api_endpoint = api_endpoint
        self.model_name = model_name

    def process(self):
        # 加载数据和解释
        self.data_handler.load_data()
        df = self.data_handler.df

        # 初始化 UserInputHandler 并传递术语解释和对话历史
        self.user_input_handler = UserInputHandler(self.user_input, self.api_endpoint, self.model_name, explanations=self.data_handler.get_all_terms(), conversation_history=self.session_manager.format_for_model())

        # 解析用户输入
        query_code_or_response = self.user_input_handler.parse_query(df)

        if "result =" in query_code_or_response:
            # 执行生成的查询代码
            self.query_executor = QueryExecutor(query_code_or_response)
            result = self.query_executor.execute(df)

            # 显示结果
            self.result_presenter = ResultPresenter(result)
            self.result_presenter.display()

        else:
            # 直接显示自然语言响应
            print(query_code_or_response)

        # 将当前对话记录到对话历史中
        self.session_manager.add_to_history(self.user_input, query_code_or_response)

        # 更新记忆
        self.memory_handler.update_memory("last_query_result", query_code_or_response)



